package cn.web03.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UploadService {
    String key;

    @Autowired
    private COSClient cosClient;

    @Value("${cos.SECRET_ID}")
    private String SECRET_ID;
    @Value("${cos.SECRET_KEY}")
    private String SECRET_KEY;
    @Value("${cos.REGION_NAME}")
    private String REGION_NAME;
    @Value("${cos.BUCKET_NAME}")
    private String BUCKET_NAME;


    public String uploadImage(MultipartFile file){
        // 支持的文件类型
        List<String> suffixes = Arrays.asList("image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp", "image/bmp");
        String filePath = "/blog/images/";
        return upload(file,suffixes,filePath);
    }
    public String uploadFile(MultipartFile file){
        // 支持的文件类型
        List<String> suffixes = Arrays.asList(
                "text/html",
                "text/plain",
                "application/javascript",
                "text/css",
                "application/x-zip-compressed",
                "application/zip",
                "application/gzip",
                "application/pdf",
                "application/vnd.android.package-archive",
                "application/msword",
                "application/octet-stream",
                "application/x-msdownload",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        
        String filePath = "/blog/files/";
        return upload(file,suffixes,filePath);
    }

    public String upload(MultipartFile file, List<String> suffixes, String filePath) {
        try {
            // 1、图片信息校验
            // 1)校验文件类型
            String type = file.getContentType(); //获取文件格式
            System.out.println("文件类型："+type);
            if (!suffixes.contains(type)) {
                 System.out.println("上传失败，文件类型不匹配：{}");
                return null;
            }
            if ("blog/images/".equals(filePath)){
                // 2)校验图片内容
                BufferedImage image = ImageIO.read(file.getInputStream());
                if (image == null) {
                    System.out.println("上传失败，文件内容不符合要求");
                    return null;
                }
            }
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(type);
            UUID uuid = UUID.randomUUID();
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            // 指定要上传到 COS 上对象键 此key是文件唯一标识
            key = filePath + uuid.toString().replace("-","")+"."+suffix;
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, file.getInputStream(),objectMetadata);
            //使用cosClient调用第三方接口
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            cosClient.shutdown();
            //返回路径

        }catch (Exception e){
            e.printStackTrace();
        }
        //拼接返回路径
        String imagePath = "https://" + BUCKET_NAME + ".cos." + REGION_NAME + ".myqcloud.com" + key;
        return imagePath;
    }

}